const { app, BrowserWindow, Menu, dialog, Tray, ipcMain } = require('electron');
const { exec } = require('child_process');
const fsPromises = require('fs').promises;
const fs = require('fs');
const path = require('path');
const iconv = require('iconv-lite');
let mainWindow;
let tray;
// 总文件大小
let totalSize = 0;
// 已复制的总字节数
let totalCopied = 0;
// 倒计时相关变量
let shutdownTimer = null;
let remainingSeconds = 0;

process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true'
function createWindow() {
    const iconPath = process.platform === 'win32' ? path.join(__dirname, 'build', 'icon.ico') : path.join(__dirname, 'build', 'icon.png');
    mainWindow = new BrowserWindow({
        width: 1200,
        height: 600,
        title: 'myapp',// 应用标题
        icon: iconPath,
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
            contentSecurityPolicy: "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:;"
        }
    });
    mainWindow.loadFile('index.html');
    createTray(iconPath);
    const menu = Menu.buildFromTemplate([
        {
            label: '简介',
            submenu: [
                {
                    label: '简介',
                    click() {
                        dialog.showMessageBox(mainWindow, {
                            type: 'info',
                            title: '简介',
                            message: '这是一个文件同步工具。',
                            buttons: ['确定']
                        });
                    }
                }
            ]
        },
        {
            label: '试用人员',

            submenu: [
                {
                    label: '试用人员',
                    click() {
                        dialog.showMessageBox(mainWindow, {
                            type: 'info',
                            title: '试用人员',
                            message: '粥粥粥',
                            buttons: ['确定']
                        });
                    }
                }
            ]
        }
    ])
    Menu.setApplicationMenu(menu)
    // 监听窗口关闭事件
    mainWindow.on('close', (e) => {
        if (app.isQuitting) {
            // 如果是用户主动退出应用，则正常关闭
            mainWindow = null;
        } else {
            // 阻止默认关闭行为，隐藏窗口
            e.preventDefault();
            mainWindow.hide();
        }
    });
}


function createTray(iconPath) {
    try {
        if (tray) {
            return;
        }
        tray = new Tray(iconPath);
        tray.setToolTip('系统小工具Max'); // 添加这行设置悬停提示
        const contextMenu = Menu.buildFromTemplate([
            {
                label: '显示窗口',
                click: () => {
                    if (mainWindow) {
                        // 若窗口存在，不管是否销毁，都尝试显示
                        if (mainWindow.isDestroyed()) {
                            // 若窗口已销毁，重新创建
                            createWindow();
                        } else {
                            // 若窗口未销毁，直接显示
                            mainWindow.show();
                        }
                    } else {
                        // 若窗口不存在，重新创建
                        createWindow();
                    }
                }
            },
            {
                label: '退出',
                click: () => {
                    app.isQuitting = true;
                    app.quit();
                }
            }
        ]);
        tray.setContextMenu(contextMenu);
        tray.on('click', () => {
            if (mainWindow) {
                // 若窗口存在，不管是否销毁，都尝试显示
                if (mainWindow.isDestroyed()) {
                    // 若窗口已销毁，重新创建
                    createWindow();
                } else {
                    // 若窗口未销毁，直接显示
                    mainWindow.show();
                }
            } else {
                // 若窗口不存在，重新创建
                createWindow();
            }
        });

    } catch (error) {
        log(`创建托盘图标时出错: ${error.message}`);
    }
}
function shutdownAfterDelay(delay) {
    return new Promise((resolve, reject) => {
        
 
    // Windows 系统使用 shutdown 命令，/s 表示关机，/t 后面跟延迟时间（秒）
    const command = `shutdown /s /t ${delay}`;

    // 以管理员权限执行关机命令
    const adminCommand = `powershell -Command "Start-Process cmd -ArgumentList '/c ${command}' -Verb RunAs"`;

    // 执行关机命令
    exec(adminCommand, (error, _, stderr) => {
        if (error) {
           log(`执行命令时出错: ${error.message}`);
            return;
        }
        if (stderr) {
            log(`命令执行错误输出: ${stderr}`);
            return;
        }
        log(`已设置在 ${delay} 秒后关机`);
        resolve()
    });
       })
}

/**
 * 取消 Windows 系统已设置的关机计划
 */
function cancelShutdown() {
    return new Promise((resolve, reject) => {
         // Windows 系统使用 shutdown 命令，/a 表示取消关机
    const command = 'shutdown /a';

    // 以管理员权限执行取消关机命令
    const adminCommand = `powershell -Command "Start-Process cmd -ArgumentList '/c ${command}' -Verb RunAs"`;

    // 执行取消关机命令
    exec(adminCommand, (error, _, stderr) => {
        if (error) {
            log(`执行命令时出错: ${error.message}`);
            return;
        }
        if (stderr) {
            log(`命令执行错误输出: ${stderr}`);
            return;
        }
        log('已取消关机计划');
        resolve()
    });
    })
   
}

// // 使用示例：设置 10 秒后关机
// // shutdownAfterDelay(10);
// // 使用示例：取消关机计划
// cancelShutdown();

ipcMain.handle('schedule-shutdown', (event, { t, close }) => {
    return new Promise((resolve) => {
        if (!close) {
            // 启动倒计时
            startShutdownCountdown(t);
            shutdownAfterDelay(t).then(() => {
                resolve({ success: true, message: `设置关机成功` });
            });
        } else {
            // 取消倒计时
            stopShutdownCountdown();
            cancelShutdown().then(() => {
                resolve({ success: true, message: `取消关机成功` });
            });
        }
    });
});

ipcMain.on('work', (event, arg) => {
    main(arg)
        .then(() => {
            // 处理成功，向渲染进程发送消息
            event.sender.send('work-result', { success: true, message: '处理成功' });
        })
        .catch(err => {
            log('主程序错误:', err);
            // 处理失败，向渲染进程发送消息
            event.sender.send('work-result', { success: false, message: err, error: err });
        }).finally(() => {
            log('主程序执行完毕');

        });
});












// 请求单实例锁
const gotTheLock = app.requestSingleInstanceLock();

if (!gotTheLock) {
    // 若没获取到锁，说明已有实例在运行，直接退出
    app.quit();
} else {
    // 监听第二个实例启动事件
    app.on('second-instance', (event, commandLine, workingDirectory) => {
        if (mainWindow) {
            if (mainWindow.isMinimized()) mainWindow.restore();
            mainWindow.show();
            mainWindow.focus();
        }
    });

    // 当应用准备好时创建窗口
    app.whenReady().then(createWindow);
}

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        // 不调用 app.quit()，让应用继续在后台运行
    }
});


app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
        createWindow()
    }
})


// 日志函数
function log(msg) {
    const time = new Date().toISOString();
    const log = `[${time}] ${msg}\n`
    const winEncoding = 'gbk' // Windows 中文系统通常使用 gbk
    const buffer = iconv.encode(log, winEncoding)
    process.stdout.write(buffer)
}

// 确保目录存在
async function ensureDirExists(dirPath) {
    try {
        await fsPromises.access(dirPath);
    } catch {
        await fsPromises.mkdir(dirPath, { recursive: true });
        log(`已创建目录：${dirPath}`);
    }
}

/**
 * 计算目录下所有文件的总大小
 * @param {string} dir 目录路径
 */
async function calculateTotalSize(dir) {
    let size = 0;
    const items = await fsPromises.readdir(dir, { withFileTypes: true });
    for (const item of items) {
        const itemPath = path.join(dir, item.name);
        if (item.isDirectory()) {
            size += await calculateTotalSize(itemPath);
        } else {
            const stats = await fsPromises.stat(itemPath);
            size += stats.size;
        }
    }
    return size;
}

/**
 * 复制源目录到目标目录
 * @param {string} src 源目录路径
 * @param {string} dest 目标目录路径
 */
async function syncDirectories(src, dest) {
    try {
        log(`开始处理源目录：${src}，目标目录：${dest}`);
        // 检查源目录是否存在
        await fsPromises.access(src, fsPromises.constants.R_OK);
        log(`源目录 ${src} 存在，开始读取内容`);

        const items = await fsPromises.readdir(src, { withFileTypes: true });

        await ensureDirExists(dest);
        log(`目标目录 ${dest} 已确保存在`);

        for (const item of items) {
            const srcPath = path.join(src, item.name);
            const destPath = path.join(dest, item.name);

            if (item.isDirectory()) {
                log(`进入子目录 ${srcPath}，准备递归同步`);
                await syncDirectories(srcPath, destPath);
            } else {
                log(`开始复制文件 ${srcPath} 到 ${destPath}`);
                await copyFileWithProgress(srcPath, destPath);
                log(`已复制文件：${srcPath} -> ${destPath}`);
            }
        }
        log(`完成处理源目录：${src}`);
    } catch (err) {
        log(`处理失败：${src} -> ${dest}，错误信息：${err.message}`);
        // 抛出错误，让上层函数处理
        throw err;
    }
}

/**
 * 带进度显示的文件复制函数
 * @param {string} src 源文件路径
 * @param {string} dest 目标文件路径
 */
async function copyFileWithProgress(src, dest) {
    const stats = await fsPromises.stat(src);
    const fileSize = stats.size;

    return new Promise((resolve, reject) => {
        const readStream = fs.createReadStream(src);
        const writeStream = fs.createWriteStream(dest);

        readStream.on('data', (chunk) => {
            const chunkLength = chunk.length;
            totalCopied += chunkLength;
            const totalProgress = (totalCopied / totalSize) * 100;
            // 发送总进度信息到渲染进程
            mainWindow.webContents.send('total-file-copy-progress', {
                progress: totalProgress
            });
        });

        readStream.pipe(writeStream);

        writeStream.on('finish', () => {
            resolve();
        });

        writeStream.on('error', (err) => {
            reject(err);
        });
    });
}

/**
 * 同步多个目录对
 * @param {Array} dirPairs 数组，每个元素是一个对象，包含 src 和 dest 属性
 */
async function syncMultipleDirs(dirPairs) {
    // 重置总大小和已复制字节数
    totalSize = 0;
    totalCopied = 0;
    // 计算所有需要复制文件的总大小
    for (const pair of dirPairs) {
        totalSize += await calculateTotalSize(pair.src);
    }
    for (const pair of dirPairs) {
        await syncDirectories(pair.src, pair.dest);
    }
}

// 主函数
async function main(array) {
    log('开始同步文件...');
    if (!array || array.length === 0) {
        log('未传入需要同步的目录对');
        throw new Error('未传入需要同步的目录对');
    }

    // 执行同步
    await syncMultipleDirs(array);
    log('所有同步任务完成。');
}

ipcMain.handle('save-config', async (event, data) => {
    const { canceled, filePath } = await dialog.showSaveDialog({
        title: '选择保存路径',
        defaultPath: 'sync_config.json',
        filters: [
            { name: 'JSON Files', extensions: ['json'] },
            { name: 'All Files', extensions: ['*'] }
        ]
    });

    if (canceled) {
        return { success: false, message: '用户取消保存' };
    }

    try {
        await fsPromises.writeFile(filePath, data, 'utf8');
        return { success: true, message: '导出成功' };
    } catch (error) {
        return { success: false, message: `导出失败: ${error.message}` };
    }
});



ipcMain.handle('dev', (event, arg) => {
    arg ? mainWindow.webContents.openDevTools() : mainWindow.webContents.closeDevTools()
});

// 修改d.js中的convertToWebP函数，添加回调参数

// const { ipcMain, dialog } = require('electron');

// Add this handler for opening directory dialog
ipcMain.handle('open-directory-dialog', async () => {
    return await dialog.showOpenDialog({
        properties: ['openDirectory'],
        title: '选择要转换图片的目录'
    });
});

// Add this handler for image conversion
ipcMain.handle('convert-images', async (event, inputDir) => {
    const { convertToWebP } = require('./d.js');
    const outputDir = path.join(inputDir, 'converted_images');

    try {
        const result = await new Promise((resolve, reject) => {
            convertToWebP(inputDir, outputDir, (err, result) => {
                if (err) reject(err);
                else resolve(result);
            });
        });
        return { converted: result.converted };  // 返回实际转换数量
    } catch (err) {
        throw err;
    }
});


// 倒计时函数
function startShutdownCountdown(seconds) {
    // 清除现有的定时器
    if (shutdownTimer) {
        clearInterval(shutdownTimer);
    }
    
    remainingSeconds = seconds;
    
    // 通知渲染进程开始倒计时
    if (mainWindow) {
        mainWindow.webContents.send('shutdown-countdown-start', { totalSeconds: seconds });
    }
    
    // 启动新的倒计时
    shutdownTimer = setInterval(() => {
        remainingSeconds--;
        
        // 通知渲染进程更新剩余时间
        if (mainWindow) {
            mainWindow.webContents.send('shutdown-countdown-update', { remainingSeconds });
        }
        
        // 当倒计时结束时
        if (remainingSeconds <= 0) {
            clearInterval(shutdownTimer);
            shutdownTimer = null;
            
            // 通知渲染进程倒计时结束
            if (mainWindow) {
                mainWindow.webContents.send('shutdown-countdown-end');
            }
        }
    }, 1000);
}

function stopShutdownCountdown() {
    if (shutdownTimer) {
        clearInterval(shutdownTimer);
        shutdownTimer = null;
        remainingSeconds = 0;
        
        // 通知渲染进程取消倒计时
        if (mainWindow) {
            mainWindow.webContents.send('shutdown-countdown-cancel');
        }
    }
}